import 'dart:io';
import 'dart:typed_data';

import 'dart:ui' as ui; //这里添加下标识，防止冲突
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'path_provider_utils.dart';

/**
 * @Description: 图片水印工具类
 * @Author: 下雨了
 * @CreateDate: 2022-08-04 9:19
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-08-04 9:19
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///

class WatermarkImageUtils {
  // 私有构造函数
  WatermarkImageUtils._internal();

  // 保存单例
  static final WatermarkImageUtils _imageUtils =
      WatermarkImageUtils._internal();

  // 工厂构造函数
  factory WatermarkImageUtils() => _imageUtils;

  //拿到图片的字节数组
  Future<ui.Image> loadImageByFile(String path) async {
    Uint8List list = await File(path).readAsBytes();
    return loadImageByUint8List(list);
  }

  //通过[Uint8List]获取图片
  Future<ui.Image> loadImageByUint8List(Uint8List list) async {
    ui.Codec codec = await ui.instantiateImageCodec(list);
    ui.FrameInfo frame = await codec.getNextFrame();
    return frame.image;
  }

  //图片加文字
  Future<File> imageAddWaterMark(String imagePath) async {
    int width, height;

    //拿到Canvas
    ui.PictureRecorder recorder = new ui.PictureRecorder();

    Canvas canvas = new Canvas(recorder);

    //拿到Image对象
    ui.Image image = await loadImageByFile(imagePath);
    width = image.width;
    height = image.height;

    //在Canvas上画Image
    canvas.drawImage(image, Offset(0, 0), Paint());

    ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle(
      textAlign: TextAlign.start,
      fontWeight: FontWeight.normal,
      fontStyle: FontStyle.normal,
      fontSize: 14.r,
    ))
      ..pushStyle(ui.TextStyle(color: Colors.black))
      ..addText('我是你的水印\n我是你的水印我是你的水印')
      ..addText('text');

    ui.ParagraphConstraints pc =
        ui.ParagraphConstraints(width: width.toDouble());
    ui.Paragraph paragraph = pb.build()..layout(pc);

    canvas.drawParagraph(paragraph, Offset(0, 0));

    ui.Picture picture = recorder.endRecording();

    final img = await picture.toImage(width.toInt(), height.toInt());

    final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);

    final Directory _directory = await PathProviderUtils().getCacheDir();
    final Directory _imageDirectory =
        await new Directory('${_directory.path}/image/')
            .create(recursive: true);
    String _targetPath = _imageDirectory.path;

    File file = File(
        '${_targetPath}watermark${DateTime.now().millisecondsSinceEpoch}.png');

    file.writeAsBytesSync(pngBytes!.buffer.asInt8List());

    return file;
  }


  // 图片上 添加图片水印 并覆盖 底板图片
  // imagePath        底板图片
  // imageWaterPath   水印图片
  Future<File> imageAddImageWaterMark(
    String imagePath,
    String imageWaterPath, {
    double waterDx = 10.0,
    double waterDy = 10.0,
  }) async {

    int width, height;

    //拿到Canvas
    ui.PictureRecorder recorder = new ui.PictureRecorder();
    // 创建 canvas
    Canvas canvas = new Canvas(recorder);

    //拿到Image对象
    ui.Image image = await loadImageByFile(imagePath);
    width = image.width;
    height = image.height;

    //在Canvas上画Image
    canvas.drawImage(image, Offset(0, 0), Paint());
    // 拿到 水印image对象
    ui.Image imageWater = await loadImageByFile(imageWaterPath);
    //在Canvas上画 水印
    canvas.drawImage(imageWater, Offset(waterDx, waterDy), Paint());

    // 完成 绘制
    ui.Picture picture = recorder.endRecording();

    final ui.Image img = await picture.toImage(width.toInt(), height.toInt());

    final ByteData? pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
    // 覆盖 底本文件
    File file = File(imagePath);
    // 保存文件
    file.writeAsBytesSync(pngBytes!.buffer.asInt8List());

    return file;
  }


}
